package com.iamteer.b_upload;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUpload
 */
@WebServlet("/FileUpload")
public class FileUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. 创建工厂类
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 2. 创建文件上传核心类对象，并设置
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(1 * 1024 * 1024);		// 单个最大 1M
		upload.setSizeMax(10 * 1024 * 1024);		// 总共最多 10M
		
		// 3. 判断表单是否为文件上传表单
		if (ServletFileUpload.isMultipartContent(request)) {
			try {
				// 4. 把请求数据转换为 FileItem 集合
				List<FileItem> list = upload.parseRequest(request);
				
				// 5. 遍历 FileItem
				for (FileItem item : list) {
					// 6. 判断是普通表单还是文件表单
					if (item.isFormField()) {
						// 普通表单
						String fieldName = item.getFieldName();	// 元素名称
						String value = item.getString("utf-8");	// 值
						
						System.out.println(fieldName + " : " + value);
					} else {
						// 文件表单
//						String fieldName = item.getFieldName();	// 元素名称
						String name = item.getName();			// 文件名
						String basePath = "/Users/Chuck/Downloads";
						System.out.println(basePath);
						// 创建文件对象
						File file = new File(basePath, name);
						item.write(file);
						item.delete();
					}
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
